package com.ys.controller.api.amazonorder;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.bo.util.DateUtil;
import com.ys.config.MenuId;
import com.ys.entity.amazonorder.TpAmazonShopOrder;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.business.YsbExportLogService;
import com.ys.service.business.YsbExportLogService.ExportDto;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tpAmazonShopOrder")
public class ApiInterTpAmazonShopOrderController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<TpAmazonShopOrder> commonApiService;
	@Autowired
	private YsbExportLogService ysbExportLogService;

	@RequiresPermissions("tpAmazonShopOrder:view")
	@RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TpAmazonShopOrder cond,
			String conditions){

		cond = commonApiService.dataAuth(MenuId.TP_AmazonShopOrder, cond);
		
		String _ys_year = ConditionUtil.getConditionValue(conditions, "_ys_year");
		
		if (_ys_year != null && _ys_year.length() == 4) {
			
			if (_ys_year.compareTo("2024") >= 0) {
				cond.setMainTable("kjecp_amazonorder.dbo.TP_AmazonShopOrder");
			} else {
				cond.setMainTable("kjecp_amazonorder.dbo.TP_AmazonShopOrder_" + _ys_year);
			}
				
		} else {
			cond.where("1=0");
		}
		cond.setOrderby("A.PurchaseDate desc");
		
		LayuiTableVoJA vo = commonApiService.searchLay(cond);
		{
			JSONObject JO = new JSONObject();
			
			
			List<Map<String, Object>> listMap = cond.setFields("ISNULL(SUM(QuantityOrdered),0) aa, ISNULL(SUM(OrderAmount),0) bb").queryMapNoOrder();
			
			// 订单数累计
			JO.put("quantityOrdered", "合计:" + listMap.get(0).get("aa"));
			
			// 订单总金额累计
			JO.put("orderAmount", "合计:" + listMap.get(0).get("bb"));


			vo.addRows(JO);
		}
		return vo;
	}

	@RequiresPermissions("tpAmazonShopOrder:view")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TpAmazonShopOrder cond, String conditions) throws Exception{
		System.out.println(conditions);

		cond = commonApiService.dataAuth(MenuId.TP_AmazonShopOrder, cond);
		
		cond.setPage(0).setSize(999999);
		
		String _ys_year = ConditionUtil.getConditionValue(conditions, "_ys_year");
		
		if (_ys_year != null && _ys_year.length() == 4) {

			if (_ys_year.compareTo("2023") >= 0) {
				cond.setMainTable("kjecp_amazonorder.dbo.TP_AmazonShopOrder");
			} else {
				cond.setMainTable("kjecp_amazonorder.dbo.TP_AmazonShopOrder_" + _ys_year);
			}
			
			String localDate = ConditionUtil.getConditionValue(conditions, "localDate");
			if (localDate != null && localDate.length() > 0) {
				
				String[] localDates = localDate.split(" ~ ");
				String localDateBegin = localDates[0];
				String localDateEnd = localDates[1];
				
				String max = DateUtil.getYYYY_MM_DD(DateUtil.addDays(DateUtil.parseYYYY_MM_dd(localDateBegin.substring(0, 10)), 35));
				if (localDateEnd.compareTo(max) < 0) {
					
					ExportDto dto1 = ysbExportLogService.init(MenuId.TP_AmazonShopOrder);
					if (dto1.getCode() == ExportDto.Code.FAILED.value) {
						return R.error(dto1.getMsg());
					} else {
						
						try {
							cond.setOrderby("A.PurchaseDate desc");

							List<Map<String, Object>> listData = cond.queryMap();
					        
					    	List<YsCol> listField = new YsCol()
					    			.setMenuId(MenuId.TP_AmazonShopOrder)
					    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
					    			.setOrderby("A.SortNo asc")
					    			.queryList();
					    	
					        ExportExcelUtils<TpAmazonShopOrder> util = new ExportExcelUtils<TpAmazonShopOrder>(new TpAmazonShopOrder());
					        String toFilePath = util.exportExcel(listData, listField, "历年店铺订单");
					        
					        UploadDto dto2 = commonApiService.uploadLocalToServer(toFilePath);
					        ysbExportLogService.updateSuccess(dto1.getId(), dto2.getUrl());;
					        
					        return R.ok("已经生成完毕");
						} catch (Exception e) {
							e.printStackTrace();
							ysbExportLogService.updateFail(dto1.getId());
					        return R.error("生成失败，请联系客服");
						}
					}
				} else {
			        return R.error("时间范围不得超过35天");
				}
			} else {
		        return R.error("必须选择时间范围");
			}
		} else {
	        return R.error("必须选择年份");
		}
    }
}
